# web/dispatch.py
#
#

__copyright__ = 'this file is in the public domain'

from plugs.webserver import httpd
from gozerbot.fleet import fleet
from gozerbot.ircevent import Ircevent
from gozerbot.plugins import plugins
from cgi import escape
from urllib import unquote_plus
import Queue, time

def handle_dispatch(event):
    input = unquote_plus(event.path)
    bot = fleet.byname('main')
    ievent = Ircevent()
    try:
        what = input.split('?', 1)[1]
    except IndexError:
        return ["dispatch what ?",]
    if what.startswith("command="):
        what = what[8:]
    dowait = 0
    if ' wait' in what:
        what = what.rsplit(' wait')[0]
        dowait = 1
    ievent.txt = what
    ievent.nick = 'web'
    ievent.userhost = 'web@web'
    ievent.channel = 'web'
    q = Queue.Queue()
    ievent.queues.append(q)
    ievent.speed = 10
    ievent.bot = bot
    result = []
    if plugins.trydispatch(bot, ievent):
        while 1:
            res = q.get()
            if not res:
                break
            result.append(res)
    if not result:
        return ["can't dispatch %s" % what, ]
    return result

if httpd:
    httpd.addhandler('dispatch', handle_dispatch)
